---
title: "study1-data-tables"
output: html_document
---

<!-- Set working directory -->

```{r setup, include=FALSE, cache=FALSE}
rm(list=ls())
require("knitr")

# set your own working directory by adjusting the below line - to where you saved the replication files:
#eg knitr::opts_knit$set(root.dir = "~/Downloads/replication-files")

knitr::opts_knit$set(root.dir = "C:/Users/qs932404/Dropbox/USmidterms/R&R EJPR/Final submission/replication-files")

sessionInfo()

```


<!--Load all the required libraries in-->

```{r libraries, include=FALSE, cache = FALSE}


library(tidyr)

library(dplyr)

library(stringr)


library(estimatr)
```


```{r theme}


theme_report_forcovar_wlegend <- function(base_size = 14) {
  theme_bw(base_size = base_size) %+replace%
    theme(
      # L'ensemble de la figure
      plot.title = element_text(size = rel(1), face = "bold", margin = margin(0,0,5,0), hjust = 0),
      # Zone où se situe le graphique
      panel.grid.minor = element_blank(),
       panel.grid.major = element_blank(),
      panel.border = element_blank(),
      # Les axes
      axis.title = element_text(size = rel(0.85), face = "bold"),
      axis.text = element_text(size = rel(0.70), face = "bold"),
      axis.line = element_line(color = "black"),
      # La légende
      #legend.position = "none",
      legend.title = element_text(size = rel(0.85), face = "bold"),
      legend.text = element_text(size = rel(0.70), face = "bold"),
      legend.key = element_rect(fill = "transparent", colour = NA),
      legend.key.size = unit(1.5, "lines"),
      legend.background = element_rect(fill = "transparent", colour = NA),
      # Les étiquettes dans le cas d'un facetting
      strip.background = element_rect(fill = "#17252D", color = "#17252D"),
      strip.text = element_text(size = rel(0.85), face = "bold", color = "white", margin = margin(5,0,5,0))
    )
}


```

# Load data in 

```{r read}


data <- read.csv("study1_data.csv")



```

# Create new directories for output 

```{r dirs}

dir.create("data_for_figures")

dir.create("figures")

```

# Recode political violence outcome

```{r recodedv}



data <- data %>% mutate (w2_pv1_bin = if_else(w2_pv1_str=="Never", 0,1),
                         w2_pv2_bin = if_else(w2_pv2_str=="Never", 0,1),
                         w2_pv3_bin = if_else(w2_pv3_str=="Not at all", 0,1),
                         w2_pv4_bin = if_else(w2_pv4_str=="Not at all", 0,1))



data <- data %>% rowwise()  %>% mutate (w2_pv1_normalized = (w2_pv1 - 1) / (4-1),
                         w2_pv2_normalized = (w2_pv2 - 1) / (4-1),
                         w2_pv3_normalized = (w2_pv3 - 1) / (5-1),
                         w2_pv4_normalized = (w2_pv4 - 1) / (5-1),
                         w2_viol_index = mean (c(w2_pv1_normalized,w2_pv2_normalized,w2_pv3_normalized), na.rm=T))

data <- data %>%
  mutate(across(c(w2_pv1_str, w2_pv2_str), ~ factor(.x , levels= c("Never", "Occasionally","Frequently",  "Always"))))

data <- data %>%
  mutate(across(c(w2_pv3_str, w2_pv4_str), ~ factor(.x , levels= c("Not at all", "A little", "A moderate amount", "A lot", "A great deal"))))
         


data <- data %>% mutate (w1_pv1_bin = if_else(w1_pv1==1, 0,1),
                         w1_pv2_bin = if_else(w1_pv2==1, 0,1),
                         w1_pv3_bin = if_else(w1_pv3==1, 0,1),
                         w1_pv4_bin = if_else(w1_pv4==1, 0,1))



data <- data %>% rowwise()  %>% mutate (w1_pv1_normalized = (w1_pv1 - 1) / (4-1),
                         w1_pv2_normalized = (w1_pv2 - 1) / (4-1),
                         w1_pv3_normalized = (w1_pv3 - 1) / (5-1),
                         w1_pv4_normalized = (w1_pv4 - 1) / (5-1),
                         w1_viol_index = mean (c(w1_pv1_normalized,w1_pv2_normalized,w1_pv3_normalized), na.rm=T))

summary(data$w1_viol_index)
summary(data$w2_viol_index)

# create pre-post viol index 

data <- data %>% rowwise() %>% mutate(prepost_viol_index = w2_viol_index - w1_viol_index,
                                      prepost_viol_1 = w2_pv1_normalized - w1_pv1_normalized,
                                      prepost_viol_2 = w2_pv2_normalized - w1_pv2_normalized,
                                      prepost_viol_3 = w2_pv3_normalized - w1_pv3_normalized,
                                      prepost_viol_4 = w2_pv4_normalized - w1_pv4_normalized)

summary(data$prepost_viol_4)        
```

# Recode Democratic Norms 

```{r recodedn, echo=F}


# higher values on DN2-DN9 indicate higher support for democratic norms (i.e. disagreement with statements = pro democratic norm)
#reverse code DN1

data <- data %>% mutate(w2_dem_norms1_num_rv = case_when(w2_dem_norms1_num==1 ~ 7,
                                                         w2_dem_norms1_num==2 ~ 6,
                                                         w2_dem_norms1_num==3 ~ 5,
                                                         w2_dem_norms1_num==4 ~4,
                                                         w2_dem_norms1_num==5~3,
                                                         w2_dem_norms1_num==6~2,
                                                         w2_dem_norms1_num==7~1))




 
 data <- data %>% rowwise() %>% mutate(w2_dem_norms_index = mean(c(w2_dem_norms1_num_rv, w2_dem_norms2_num, w2_dem_norms3_num, w2_dem_norms4_num, w2_dem_norms5_num, w2_dem_norms6_num, w2_dem_norms7_num, w2_dem_norms8_num), na.rm=T))
 

 
```

# Recode Affective Polarization and party importance

```{r pretrecode, echo=F}


data <- data %>% rowwise() %>% mutate(w1_ap_voters = w1_ap_ingroup_voters - w1_ap_outvoters,
w1_ap_party = w1_ap_ingroup_party - w1_ap_outparty)


data <- data %>% mutate (w1_party_importance_num = as.numeric(na_if(w1_party_importance_num, 0)))

data <- data %>% mutate(w2_party_importance_num = as.numeric(na_if(w2_party_importance, "Don't know")))



```


# Recode treatment variable

```{r treatrecode, echo=F}


data <- data %>% mutate(w2_treatment_cat = case_when(grepl("anger", w2_treatment) ~ "Anger",
                                                     grepl("worry", w2_treatment) ~ "Worry",
                                                     grepl("placebo", w2_treatment) ~ "Placebo"),
                        w2_treatment_cat= factor(w2_treatment_cat, levels = c("Placebo", "Anger", "Worry")),
                        w2_treatment_tvscontrol = case_when(w2_treatment_cat=="Anger"|w2_treatment_cat=="Worry"~ "Treatment",
                                                            w2_treatment_cat =="Placebo"~"Placebo"),
                        w2_treatment_angerasref = factor(w2_treatment_cat, levels = c("Anger", "Worry", "Placebo")))

```

# Recode covariates

```{r covarsrecode}

data <- data %>% mutate(w1_gender_female = case_when(w1_gender=="Female" ~1,
                                                     TRUE~ 0),
                        w1_education_advanced = case_when(grepl( "degree", w1_education) ~ 1,
                                                          TRUE ~ 0),
                        w1_ethnicity_white = case_when(grepl("White", w1_ethnicity) ~1,
                                                       TRUE ~0),
                        w1_income_above70k = case_when(w1_income=="$70 000 - $99 999" | w1_income=="$100 000 - $200 000" ~1,
                                                       TRUE~0),
                        w1_pid = case_when(grepl("Democrat", w1_partyid_num) ~ "Democrat",
                                           grepl("Republican", w1_partyid_num) ~ "Republican"),
                        w1_partyid = case_when(grepl("Democrat", w1_partyid_num) ~ "Democrats",
                                           grepl("Republican", w1_partyid_num) ~ "Republicans"))



```

# Regression function

```{r regfunc}
# takes dependent variable list as input
#returns clean dataframe with regression output for pooled treatment and separate treatments


run_regression_models <- function(dv_cols, data) {
  library(dplyr)
  library(stringr)
  
  output <- list()
  output_df_list <- list()
  
  # Loop for treatment_factor
  for (i in seq_along(dv_cols)) {
    model <- lm_robust(as.formula(paste(dv_cols[[i]], "~ w2_treatment_cat")), data = data)
    output[[paste0(dv_cols[[i]], "_factor")]] <- model
    
    output_df_list[[length(output_df_list) + 1]] <- data.frame(
      Model = paste0(dv_cols[[i]], " (factor)"),
      Covariate = names(model$coefficients),
      Beta_Estimate = model$coefficients,
      CI_95_LL = confint(model)[, 1],
      CI_95_UL = confint(model)[, 2],
      P_val = summary(model)$coefficients[, 4],
      stringsAsFactors = FALSE
    )
  }
  
  # Loop for treatment_pooled
  for (i in seq_along(dv_cols)) {
    model <- lm_robust(as.formula(paste(dv_cols[[i]], "~ w2_treatment_tvscontrol")), data = data)
    output[[paste0(dv_cols[[i]], "_pooled")]] <- model
    
    output_df_list[[length(output_df_list) + 1]] <- data.frame(
      Model = paste0(dv_cols[[i]], " (pooled)"),
      Covariate = names(model$coefficients),
      Beta_Estimate = model$coefficients,
      CI_95_LL = confint(model)[, 1],
      CI_95_UL = confint(model)[, 2],
      P_val = summary(model)$coefficients[, 4],
      stringsAsFactors = FALSE
    )
  }

  # Combine and annotate
  output_df_full <- do.call(rbind, output_df_list) %>%
    mutate(treatment = case_when(
      str_detect(Covariate, "Anger") ~ "Anger",
      str_detect(Covariate, "Worry") ~ "Worry",
      str_detect(Covariate, "Intercept") ~ "Placebo",
      str_detect(Covariate, "Treatment") ~ "Pooled",
      TRUE ~ NA_character_
    ))
  
  return(output_df_full)
}

```

# Main Results, DV: support for political violence

```{r resultspv}


dv_cols <- data %>% select(starts_with("prepost")) %>%  colnames(.) %>% as.list() #%>% 

output_df_full <- run_regression_models(dv_cols, data)

output_df_full <- output_df_full %>%  mutate(dv = case_when(
  str_detect(Model, "1") ~ "PV 1",
  str_detect(Model, "2") ~ "PV 2",
  str_detect(Model, "3") ~ "PV 3",
  str_detect(Model, "4") ~ "PV 4",
  str_detect(Model, "index") ~ "PV index"),
  dv = factor(dv, levels = c("PV index", "PV 1", "PV 2", "PV 3","PV 4")))


saveRDS(output_df_full, "data_for_figures/s1_f8_main_polviol.rds")



```

# Main Results, DV: Demcoratic norms

```{r resultsdemnorms}



dv_cols <- data %>% select(starts_with("w2_dem_norms")) %>% select(matches("(num|index)")) %>% select(!contains("rv")) %>% select(!contains("9")) %>% colnames(.) %>% as.list() 



output_df_full <- run_regression_models(dv_cols, data)

output_df_full <- output_df_full %>%  mutate(Model = str_remove_all(Model, "w2"),
  dv = case_when(
  str_detect(Model, "1") ~ "DN 1",
  str_detect(Model, "2") ~ "DN 2",
  str_detect(Model, "3") ~ "DN 3",
  str_detect(Model, "4") ~ "DN 4",
  str_detect(Model, "5") ~ "DN 5",
  str_detect(Model, "6") ~ "DN 6",
  str_detect(Model, "7") ~ "DN 7",
  str_detect(Model, "8") ~ "DN 8",
  str_detect(Model, "index") ~ "DN index"),
  dv = factor(dv, levels = c("DN index", "DN 1", "DN 2", "DN 3","DN 4", "DN 5", "DN 6", "DN 7", "DN 8")))


saveRDS(output_df_full, "data_for_figures/s1_f9_main_demnorms.rds")





```


# Appendix, Affective polarization

```{r ap}

dv_cols <- data %>% select(starts_with("w2_ap_")) %>% colnames(.) %>% as.list() 

output_df_full <- run_regression_models(dv_cols, data)

saveRDS(output_df_full, "data_for_figures/s1_f7_main_ap.rds")

```

# Results: Emotions - discrete



```{r resultsemos}



emo_cols <- data %>% select(starts_with("w2_emo")) %>% select(contains("num")) %>% select(!contains("factor")) %>% colnames(.) %>% as.list()

output_df_full <- run_regression_models(emo_cols, data)


output_df_full <- output_df_full %>% mutate ( dv =str_extract(Model, "(?<=w2_emo_)[^_]+"))


output_df_full <- output_df_full %>% mutate ( dv = factor(dv, levels = c("sad", "resigned","enthusiastic", "hopeful", "proud","indifferent","disgusted","disappointed", "anxious", "scared", "afraid", "aversive", "bitter", "resentful", "hateful", "outraged", "worried", "angry")),
emotiongroup= case_when(str_detect(dv, "angry|worried")~ "main",
TRUE ~ "secondary"))




saveRDS(output_df_full, "data_for_figures/s1_f6_main_emo.rds")

```

# Results for binary emotion outcomes: worried and angry 

```{r emobin}



data <- data %>% mutate(angry_bin = case_when(w2_emo_angry_num<4 ~ 0,
                                      w2_emo_angry_num>=4 & w2_emo_angry_num<6 ~ 1))



summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(angry_bin ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 




saveRDS(summaryres, "data_for_figures/s1_main_emobin_angry.rds")

# worried data

data <- data %>% mutate(worried_bin = case_when(w2_emo_worried_num<4 ~ 0,
                                      w2_emo_worried_num>=4 & w2_emo_worried_num<6 ~ 1))




library(broom)

summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(worried_bin ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 



saveRDS(summaryres, "data_for_figures/s1_main_emobin_worried.rds")


```

# Stats for Methods section text

```{r}
data %>%
  filter(w1_partyid=="Democrats") %>%
lm_robust(angry_bin ~ w2_treatment_cat, data = .) %>%
  summary(.)



```

# Results: Emotions - factors

```{r emofac}

data <- data %>% mutate(w2_emo_aversionfactor_num = mean(c(w2_emo_aversive_num, w2_emo_angry_num, w2_emo_hateful_num, w2_emo_bitter_num, w2_emo_resentful_num), na.rm=T),
                w2_emo_anxietyfactor_num = mean(c(w2_emo_worried_num, w2_emo_anxious_num, w2_emo_afraid_num, w2_emo_scared_num), na.rm=T),
                w2_emo_enthusiasmfactor_num = mean(c(w2_emo_enthusiastic_num, w2_emo_hopeful_num, w2_emo_proud_num), na.rm=T),
                w2_emo_disgustfactor_num= mean(c(w2_emo_disgusted_num, w2_emo_disappointed_num, w2_emo_indifferent_num), na.rm=T))

emo_cols <- data %>% select(starts_with("w2_emo")) %>% select(contains("num")) %>% select(contains("factor")) %>% colnames(.) %>% as.list()


output_df_full <- run_regression_models(emo_cols, data)


output_df_full <- output_df_full %>% mutate ( dv =str_extract(Model, "(?<=w2_emo_)[^_]+"))

saveRDS(output_df_full, "data_for_figures/s1_f6b_main_emofactors.rds")


```

# Appendix, perceptions of election outcome

```{r perceptions}

library(broom)

data <- data %>% mutate(treat_elecoutcome_correct = case_when(w2_prolific_political_affiliation=="Democrat" & w2_treatment_elecoutcome_hor_dems=="Republicans have won a majority in the House" ~ 1,
                                                             w2_prolific_political_affiliation=="Democrat" & w2_treatment_elecoutcome_hor_dems!="Republicans have won a majority in the House" ~0,
                                                             w2_prolific_political_affiliation=="Republican" & w2_treatment_electoutcome_senate_reps=="Democrats control the Senate" ~1,
                                                             w2_prolific_political_affiliation=="Republican" & w2_treatment_electoutcome_senate_reps!="Democrats control the Senate" ~0 ),
                        treat_elecoutcome_correct_f=factor(treat_elecoutcome_correct))

summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(treat_elecoutcome_correct ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 



saveRDS(summaryres, "data_for_figures/s1_f5_main_accuracy.rds")



```



# Text analysis outcomes


# prepare corpus

```{r prepcorp}
library(tidytext)


data <- data %>% ungroup() %>% mutate(X= row_number())
data %>% count(X)


data <- data %>% mutate(w2_opentext = case_when(w2_treatment_cat=="Placebo" ~ w2_placebo_text,
                                                w2_treatment_cat!="Placebo" ~ w2_treatment_textq))

tidy_opentext <- data %>% filter(!is.na(w2_treatment_cat)) %>%
    select(X, w2_treatment_cat,w1_partyid, w2_opentext) %>%
    unnest_tokens("word", w2_opentext)


tidy_countwords <- tidy_opentext %>% group_by(X) %>% count() 

data <- left_join(data, tidy_countwords, by="X") 


```


# Bing

```{r sentimentbing, echo=F}


library(stringr)
head(get_sentiments("bing"),50)

dislike_sentiment <- tidy_opentext %>%
  inner_join(get_sentiments("bing")) %>%
      filter(sentiment=="negative") %>%
    count(X, sentiment) %>%
  mutate(sentiment_negative = n) %>%
  select(X, sentiment_negative)



data <- data %>% full_join(., dislike_sentiment, by= "X")

data <- data %>% mutate(sentiment_negative = replace_na(sentiment_negative, 0))




dislike_sentiment <- tidy_opentext %>%
  inner_join(get_sentiments("bing")) %>%
      filter(sentiment=="positive") %>%
    count(X, sentiment) %>%
  mutate(sentiment_positive = n) %>%
  select(X, sentiment_positive)



data <- data %>% full_join(., dislike_sentiment, by= "X")

data <- data %>% mutate(sentiment_positive = replace_na(sentiment_positive, 0))


```

# Afinn 
```{r afinn}
#install.packages("textdata")
library(textdata)
dislike_sentiment <- tidy_opentext %>%
  inner_join(get_sentiments("afinn")) %>%
group_by(X) %>%
  mutate(sentiment_negative_afinn = (sum(value))*-1) %>% select(X, sentiment_negative_afinn) %>% unique() 
  



data <- data %>% full_join(., dislike_sentiment, by= "X")

data <- data %>% mutate(sentiment_negative_afinn = replace_na(sentiment_negative_afinn, 0))
```

# NRC

```{r nrc}

# Define the URL and destination path

url <- "https://saifmohammad.com/WebDocs/Lexicons/NRC-Emotion-Lexicon.zip"
dest_zip <- "nrc_emotion_lexicon.zip"
dest_dir <- "nrc_lexicon"

# Create directory if it doesn't exist
if (!dir.exists(dest_dir)) {
  dir.create(dest_dir)
}

# Download the zip file
download.file(url, destfile = file.path(dest_dir, dest_zip), mode = "wb")

# Unzip the file
unzip(file.path(dest_dir, dest_zip), exdir = dest_dir)

# Define the path to the specific file inside the unzipped folder
lexicon_file <- file.path(dest_dir, "NRC-Emotion-Lexicon", 
                          "NRC-Emotion-Lexicon-Wordlevel-v0.92.txt")

# Read the file
nrc <- read.delim(lexicon_file,
                  header = FALSE,
                  stringsAsFactors = FALSE,
                  sep = "\t")



# Rename columns for clarity
colnames(nrc) <- c("word", "emotion", "association")

# Preview the data
head(nrc)

nrc_fear <- nrc %>%
      filter(emotion=="fear") %>%
  filter(association==1)


nrc_anger <- nrc %>%
      filter(emotion=="anger")%>%
  filter(association==1)

nrc_fear_unique <- nrc_fear %>%
  anti_join(., nrc_anger, by="word")

nrc_anger_unique <- nrc_anger %>%
  anti_join(., nrc_fear, by="word")

# match on all anger and fear words even though there is overlap

dislike_sentiment <- tidy_opentext %>%
  inner_join(nrc_anger) %>%
    count(X, emotion) %>%
  mutate(sentiment_negative_anger = n) %>%
  select(X, sentiment_negative_anger)



data <- data %>% full_join(., dislike_sentiment, by= "X")

data <- data %>% mutate(sentiment_negative_anger = replace_na(sentiment_negative_anger, 0))

dislike_sentiment <- tidy_opentext %>%
  inner_join(nrc_fear) %>%
    count(X, emotion) %>%
  mutate(sentiment_negative_fear = n) %>%
  select(X, sentiment_negative_fear)



data <- data %>% full_join(., dislike_sentiment, by= "X")

data <- data %>% mutate(sentiment_negative_fear = replace_na(sentiment_negative_fear, 0))



```

```{r textgraphs}

## combined graph for all sentiment measures



dv_cols <- data %>% select(starts_with("sentiment")) %>% colnames(.) %>% as.list()


output_df_full <- run_regression_models(dv_cols, data)

output_df_full <- output_df_full %>% mutate(emotion = Model,
sentiment = case_when(str_detect(emotion,"sentiment_negative ")~ "negative sentiment (Bing)",
                      str_detect(emotion,"sentiment_positive")~ "positive sentiment (Bing)",
                    str_detect(emotion,"negative_anger") ~"anger (NRC)",
                    str_detect(emotion,"negative_fear") ~ "fear (NRC)",
                   str_detect(emotion,"negative_afinn") ~ "negative sentiment (Afinn)"))


# pull standard deviation out from data

output_df_full <- output_df_full %>% mutate(sdest = case_when(sentiment== "negative sentiment (Bing)" ~ sd(data$sentiment_negative),
sentiment=="positive sentiment (Bing)" ~ sd(data$sentiment_positive),
                                 str_detect(sentiment, "Afinn") ~ sd(data$sentiment_negative_afinn),
                                 str_detect(sentiment, "anger") ~ sd(data$sentiment_negative_anger),
                                  str_detect(sentiment, "fear") ~ sd(data$sentiment_negative_fear)))
# create standardised coefficients

output_df_full <- output_df_full  %>% mutate(across(Beta_Estimate:CI_95_UL, ~ .x/sdest))

saveRDS(output_df_full, "data_for_figures/s1_f4_main_opentext.rds")




```
## Appendix - Open text 

```{r opentextengage}

data <- data %>% 
  mutate(nwords = replace_na(n, 0))


lmmodel <- data %>%
  filter(w1_partyid=="Democrats") %>%
lm_robust(nwords~ w2_treatment_cat, data=.)


summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(nwords ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 




library(ggplot2)
#install.packages("ggdist")
library(ggdist)
data %>%
  mutate(predicted=nwords) %>%
ggplot(., aes(x=factor(w2_treatment_cat), y=predicted, color=factor(w2_treatment_cat), shape=factor(w2_treatment_cat), fill=factor(w2_treatment_cat))) +
  theme_minimal() +
stat_halfeye(
    # adjust bandwidth
    adjust = 1,
    # move to the right
    justification = -0.2,
    # remove the slub interval
    .width = 0,
    point_colour = NA,
    alpha=0.45,
    scale=0.6
  )+
  facet_wrap(~w1_partyid)+
  scale_color_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  scale_fill_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  ylim(0,100)+
  geom_point(data = summaryres, size = 3, position = position_dodge2(width = 0.8)) +
  geom_linerange(data = summaryres,
                aes(ymin = conf.low, ymax = conf.high), size=0.9, alpha=0.5, position = position_dodge2(width = 0.8)) +
  geom_linerange(data=summaryres, aes(ymin=conf.low.83, ymax=conf.high.83), size=1.5, alpha=1.5, position = position_dodge2(width = 0.8)) +
  geom_point(position=position_jitterdodge(dodge.width=0.8), alpha=0.15) +
  theme(
plot.title =element_text(size=16, colour="black", face = "bold"),
plot.subtitle = element_text(size=15, colour="black"),
axis.title.y = element_text(size=12, colour="black"),
axis.title.x = element_text(size=12,colour="black"),
axis.text.x = element_text(size=12,colour="black"),
axis.text.y =element_text(size=12,colour="black"),
legend.text = element_text(size = 12,colour="black"),
strip.text.x = element_text(size = 12,colour="black"),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_blank(),
legend.position = "none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank()
) +
    labs(x = "Treatment condition", y = "Number of words written in open text question" ,title= "Engagement with writing task (Study 1)", caption = "83% CI (thick) and 95% CI (thin)", color="Electoral loss treatment", group=NULL, shape="Electoral loss treatment", fill="Electoral loss treatment")


ggsave(file= "figures/si_s1_opentext_nwords.png",width =25, height = 17, units = "cm", dpi=320)


```


## SI opentext - top words

```{r opentexttopw}



library(tidytext)
library(SnowballC)
# remove stop words

data("stop_words")

    
top_words <-
   tidy_opentext %>%
      anti_join(stop_words) %>%
  mutate(stem = wordStem(word)) %>%
        group_by(w2_treatment_cat, w1_partyid) %>%
            count(stem) %>%
              arrange(desc(n))


# create a joint colour scheme



words_reps <- top_words %>%
  filter(w2_treatment_cat=="Placebo") %>%
  filter(w1_partyid=="Republicans")%>%
  slice_head(., n = 20) %>% pull(stem)

words_dems <- top_words %>%
  filter(w2_treatment_cat=="Placebo") %>%
  filter(w1_partyid=="Democrats")%>%
  slice_head(., n = 20) %>% pull(stem)

ab <- c(words_dems,words_reps)
ab_unique <- unique(ab)

palette1_named = setNames(object = scales::hue_pal()(length(ab_unique)), nm = ab_unique)
print(palette1_named)

# create plot 1 

g1_dems <- top_words %>%
  filter(w2_treatment_cat=="Placebo") %>%
  filter(w1_partyid=="Democrats") %>%
  slice_head(., n = 20) %>%
    ggplot(aes(x=reorder(stem, n), y=n, fill=stem))+
      geom_bar(stat="identity",  alpha=0.65)+
        theme_minimal()+
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_text(size=12),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "", y = "Frequency" ,title= "Democrats")+
          guides(fill=FALSE)+
  coord_flip()+
  scale_fill_manual(values = palette1_named)
  
# create plot 2  
 g1_reps <- 
top_words %>%
  filter(w2_treatment_cat=="Placebo") %>%
  filter(w1_partyid=="Republicans") %>%
  slice_head(., n = 20) %>%
    ggplot(aes(x=reorder(stem, n), y=n, fill=stem))+
      geom_bar(stat="identity",  alpha=0.65)+
        theme_minimal()+
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_text(size=12),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "", y = "Frequency" ,title= "Republicans")+
          guides(fill=FALSE)+
  coord_flip() + scale_y_reverse()+
  scale_fill_manual(values = palette1_named)

#install.packages("ggpubr")
library(ggpubr)
figure <- ggarrange(g1_reps,g1_dems, ncol = 2, nrow = 1)
annotate_figure(figure,top = text_grob("Most frequent word stems in the open text placebo question", color = "black", face = "bold", size = 14))

ggsave(file= "figures/si_s1_opentext_placebo_topwords.png",width =27, height = 14, units = "cm", dpi=320)

```

# Open text - anger condition

# SI, top words treatment=anger

```{r angerwords}

# create a joint colour scheme



words_reps <- top_words %>%
  filter(w2_treatment_cat=="Anger") %>%
  filter(w1_partyid=="Republicans")%>%
  slice_head(., n = 20) %>% pull(stem)

words_dems <- top_words %>%
  filter(w2_treatment_cat=="Anger") %>%
  filter(w1_partyid=="Democrats")%>%
  slice_head(., n = 20) %>% pull(stem)

ab <- c(words_dems,words_reps)
ab_unique <- unique(ab)

palette1_named = setNames(object = scales::hue_pal()(length(ab_unique)), nm = ab_unique)
print(palette1_named)

# create plot 1 

g1_dems <- top_words %>%
  filter(w2_treatment_cat=="Anger") %>%
  filter(w1_partyid=="Democrats") %>%
  slice_head(., n = 20) %>%
    ggplot(aes(x=reorder(stem, n), y=n, fill=stem))+
      geom_bar(stat="identity",  alpha=0.65)+
        theme_minimal()+
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_text(size=12),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "", y = "Frequency" ,title= "Democrats")+
          guides(fill=FALSE)+
  coord_flip()+
  scale_fill_manual(values = palette1_named)
  
# create plot 2  
 g1_reps <- 
top_words %>%
  filter(w2_treatment_cat=="Anger") %>%
  filter(w1_partyid=="Republicans") %>%
  slice_head(., n = 20) %>%
    ggplot(aes(x=reorder(stem, n), y=n, fill=stem))+
      geom_bar(stat="identity",  alpha=0.65)+
        theme_minimal()+
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_text(size=12),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "", y = "Frequency" ,title= "Republicans")+
          guides(fill=FALSE)+
  coord_flip() + scale_y_reverse()+
  scale_fill_manual(values = palette1_named)



figure <- ggarrange(g1_reps,g1_dems, ncol = 2, nrow = 1)
annotate_figure(figure,top = text_grob("Most frequent word stems in the open text Anger question", color = "black", face = "bold", size = 14))

ggsave(file= "figures/si_s1_opentext_anger_topwords.png",width =27, height = 14, units = "cm", dpi=320)



```

# SI, top words treatment=worry

```{r worrywords}

# create a joint colour scheme



words_reps <- top_words %>%
  filter(w2_treatment_cat=="Worry") %>%
  filter(w1_partyid=="Republicans")%>%
  slice_head(., n = 20) %>% pull(stem)

words_dems <- top_words %>%
  filter(w2_treatment_cat=="Worry") %>%
  filter(w1_partyid=="Democrats")%>%
  slice_head(., n = 20) %>% pull(stem)

ab <- c(words_dems,words_reps)
ab_unique <- unique(ab)

palette1_named = setNames(object = scales::hue_pal()(length(ab_unique)), nm = ab_unique)
print(palette1_named)

# create plot 1 

g1_dems <- top_words %>%
  filter(w2_treatment_cat=="Worry") %>%
  filter(w1_partyid=="Democrats") %>%
  slice_head(., n = 20) %>%
    ggplot(aes(x=reorder(stem, n), y=n, fill=stem))+
      geom_bar(stat="identity",  alpha=0.65)+
        theme_minimal()+
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_text(size=12),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "", y = "Frequency" ,title= "Democrats")+
          guides(fill=FALSE)+
  coord_flip()+
  scale_fill_manual(values = palette1_named)
  
# create plot 2  
 g1_reps <- 
top_words %>%
  filter(w2_treatment_cat=="Worry") %>%
  filter(w1_partyid=="Republicans") %>%
  slice_head(., n = 20) %>%
    ggplot(aes(x=reorder(stem, n), y=n, fill=stem))+
      geom_bar(stat="identity",  alpha=0.65)+
        theme_minimal()+
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_text(size=12),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "", y = "Frequency" ,title= "Republicans")+
          guides(fill=FALSE)+
  coord_flip() + scale_y_reverse()+
  scale_fill_manual(values = palette1_named)



figure <- ggarrange(g1_reps,g1_dems, ncol = 2, nrow = 1)
annotate_figure(figure,top = text_grob("Most frequent word stems in the open text Worry question", color = "black", face = "bold", size = 14))

ggsave(file= "figures/si_s1_opentext_worry_topwords.png",width =27, height = 14, units = "cm", dpi=320)

```

# SI opentext mean sentiment

```{r mean_opentext_bing}



## plot mean negative sentiment


summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(sentiment_negative ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 





data %>%
  mutate(predicted=sentiment_negative) %>%
ggplot(., aes(x=factor(w2_treatment_cat), y=predicted, color=factor(w2_treatment_cat), shape=factor(w2_treatment_cat), fill=factor(w2_treatment_cat))) +
  theme_minimal() +
  facet_wrap(~w1_partyid)+
  scale_color_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  scale_fill_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  ylim(0,4)+
  geom_point(data = summaryres, size = 3, position = position_dodge2(width = 0.8)) +
  geom_linerange(data = summaryres,
                aes(ymin = conf.low, ymax = conf.high), size=0.9, alpha=0.5, position = position_dodge2(width = 0.8)) +
  geom_linerange(data=summaryres, aes(ymin=conf.low.83, ymax=conf.high.83), size=1.5, alpha=1.5, position = position_dodge2(width = 0.8)) +
  geom_point(position=position_jitterdodge(dodge.width=0.8), alpha=0.15) +
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_blank(),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "Treatment condition", y = "Number of negative words used in open text question (Bing dictionary)" ,title= paste("Mean negative sentiment" , "across experimental conditions and partisanship", sep= " "), caption = "83% CI (thick) and 95% CI (thin)",color="Electoral loss treatment", group=NULL, shape="Electoral loss treatment", fill="Electoral loss treatment")


ggsave(file= "figures/si_s1_manip_opentext_sentiment_bing.png",width =25, height = 17, units = "cm", dpi=320)

## afinn




summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(sentiment_negative_afinn ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 





data %>%
  mutate(predicted=sentiment_negative_afinn) %>%
ggplot(., aes(x=factor(w2_treatment_cat), y=predicted, color=factor(w2_treatment_cat), shape=factor(w2_treatment_cat), fill=factor(w2_treatment_cat))) +
  theme_minimal() +
  facet_wrap(~w1_partyid)+
  scale_color_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  scale_fill_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  ylim(-5,5)+
  geom_point(data = summaryres, size = 3, position = position_dodge2(width = 0.8)) +
  geom_linerange(data = summaryres,
                aes(ymin = conf.low, ymax = conf.high), size=0.9, alpha=0.5, position = position_dodge2(width = 0.8)) +
  geom_linerange(data=summaryres, aes(ymin=conf.low.83, ymax=conf.high.83), size=1.5, alpha=1.5, position = position_dodge2(width = 0.8)) +
  geom_point(position=position_jitterdodge(dodge.width=0.8), alpha=0.15) +
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_blank(),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "Treatment condition", y = "Mean sentiment in open text question (Afinn dictionary) \n More negative values = more negative sentiment" ,title= paste("Mean sentiment" , "across experimental conditions and partisanship (Afinn dictionary)", sep= " "), caption = "83% CI (thick) and 95% CI (thin)",color="Electoral loss treatment", group=NULL, shape="Electoral loss treatment", fill="Electoral loss treatment")


ggsave(file= "figures/si_s1_manip_opentext_sentiment_afinn.png",width =25, height = 17, units = "cm", dpi=320)

## fear

summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(sentiment_negative_fear ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 



data %>%
  mutate(predicted=sentiment_negative_fear) %>%
ggplot(., aes(x=factor(w2_treatment_cat), y=predicted, color=factor(w2_treatment_cat), shape=factor(w2_treatment_cat), fill=factor(w2_treatment_cat))) +
  theme_minimal() +
  facet_wrap(~w1_partyid)+
  scale_color_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  scale_fill_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  ylim(0,3)+
  geom_point(data = summaryres, size = 3, position = position_dodge2(width = 0.8)) +
  geom_linerange(data = summaryres,
                aes(ymin = conf.low, ymax = conf.high), size=0.9, alpha=0.5, position = position_dodge2(width = 0.8)) +
  geom_linerange(data=summaryres, aes(ymin=conf.low.83, ymax=conf.high.83), size=1.5, alpha=1.5, position = position_dodge2(width = 0.8)) +
  geom_point(position=position_jitterdodge(dodge.width=0.8), alpha=0.15) +
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_blank(),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "Treatment condition", y = "Number of fearful words used in open text question (NRC dictionary)" ,title= paste("Mean fear-related words" , "across experimental conditions and partisanship", sep= " "), caption = "83% CI (thick) and 95% CI (thin)",color="Electoral loss treatment", group=NULL, shape="Electoral loss treatment", fill="Electoral loss treatment")


ggsave(file= "figures/si_s1_manip_opentext_sentiment_nrc_fear.png",width =25, height = 17, units = "cm", dpi=320)




summaryres <-
  data %>% 
  group_by(w2_treatment_cat, w1_partyid) %>%
  do(tidy(lm_robust(sentiment_negative_anger ~ 1, data = .))) %>%
  mutate(predicted = estimate) %>%
  mutate(conf.low.83 = estimate -(std.error*1.3722),
                          conf.high.83 = estimate + (std.error*1.3722),
         conf.low = estimate -(std.error*1.96),
                          conf.high = estimate + (std.error*1.96)) 



data %>%
  mutate(predicted=sentiment_negative_anger) %>%
ggplot(., aes(x=factor(w2_treatment_cat), y=predicted, color=factor(w2_treatment_cat), shape=factor(w2_treatment_cat), fill=factor(w2_treatment_cat))) +
  theme_minimal() +
  facet_wrap(~w1_partyid)+
  scale_color_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  scale_fill_manual(values=c('#636363','#810f7c','#43a2ca', '#636363','#810f7c','#43a2ca'))+
  ylim(0,3)+
  geom_point(data = summaryres, size = 3, position = position_dodge2(width = 0.8)) +
  geom_linerange(data = summaryres,
                aes(ymin = conf.low, ymax = conf.high), size=0.9, alpha=0.5, position = position_dodge2(width = 0.8)) +
  geom_linerange(data=summaryres, aes(ymin=conf.low.83, ymax=conf.high.83), size=1.5, alpha=1.5, position = position_dodge2(width = 0.8)) +
  geom_point(position=position_jitterdodge(dodge.width=0.8), alpha=0.15) +
  theme(
plot.title = element_text(hjust = 0, size = 12, face="bold"),
axis.title.y = element_text(size=12),
axis.title.x = element_blank(),
axis.text.x = element_text(size=12),
axis.text.y =element_text(size=12),
legend.text = element_text(size = 12),
strip.text.x = element_text(size = 12),
legend.position = "none",
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_text(size=12)
) +
    labs(x = "Treatment condition", y = "Number of angry words used in open text question (NRC dictionary)" ,title= paste("Mean anger-related words" , "across experimental conditions and partisanship", sep= " "), caption = "83% CI (thick) and 95% CI (thin)",color="Electoral loss treatment", group=NULL, shape="Electoral loss treatment", fill="Electoral loss treatment")


ggsave(file= "figures/si_s1_manip_opentext_sentiment_nrc_anger.png",width =25, height = 17, units = "cm", dpi=320)

```


## Appendix distribution graphs: emotions

```{r createdv-overview-graphs}


library(tidyverse)
#install.packages("ggridges")
library(ggridges)


emo_cols <- data %>% select(starts_with("w2_emo")) %>% select(contains("num")) %>% select(contains("factor")) %>% colnames(.)


  
dfs<- data %>% dplyr::select(all_of(c(emo_cols, "w1_partyid"))) %>%
  mutate_all(~as.character(.)) %>%
pivot_longer(
cols = starts_with("w2_emo"),
names_to = "category",
values_to = "value") %>%
  mutate(party_category=case_when(str_detect(category, "inparty")~ "In-party",
                            str_detect(category, "outparty") ~ "Out-party"),
         emotion_category = case_when(str_detect(category, "anxiety")~ "Anxiety",
                            str_detect(category, "aversion") ~ "Aversion",
                            str_detect(category, "disgust")~ "Disgust",
                            str_detect(category, "enthusiasm") ~ "Enthusiasm")) %>%
  mutate(value=as.numeric(value))
  
  
  

library(ggplot2)
ggplot(dfs, aes(x = value, y = emotion_category, fill=emotion_category)) +
  geom_density_ridges(
    jittered_points = TRUE,
    point_shape = "|", point_size = 2, size = 0.25,
    position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2,
    quantile_lines=TRUE, quantiles=2) +
  theme_classic()+
       labs(x = "Value", y="",title = "Distribution of emotions towards election outcome (Study 1)")+
  theme(
plot.title =element_text(size=16, colour="black", face = "bold"),
plot.subtitle = element_text(size=15, colour="black"),
axis.title.y = element_text(size=12, colour="black"),
axis.title.x = element_text(size=12,colour="black"),
axis.text.x = element_text(size=12,colour="black"),
axis.text.y =element_text(size=12,colour="black"),
legend.text = element_text(size = 12,colour="black"),
strip.text.x = element_text(size = 12,colour="black"),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_blank(),
legend.position = "none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank()
) +
  facet_wrap(~w1_partyid)

ggsave(file= paste("figures/si_s1_desc_emodimensions.png", sep=""),width =25, height = 17, units = "cm", dpi=320)

```

## Distribution graphs for Appendix: PV Index and DN index, AP


```{r createdv-overview-graphs-pvdn}

data <- data %>% mutate(pid_cat=w1_partyid)

dfs<- data %>% dplyr::select(all_of(c("w2_dem_norms_index", "pid_cat")))%>%
  mutate_all(~as.character(.)) %>%
pivot_longer(
cols = c("w2_dem_norms_index"),
names_to = "category",
values_to = "value") %>%
  mutate(emotion_category = case_when(str_detect(category, "viol")~ "PV index",
                            str_detect(category, "norms") ~ "DN index")) %>%
  mutate(value=as.numeric(value))
  
  
  

library(ggplot2)
ggplot(dfs, aes(x = value, y = emotion_category, fill=emotion_category)) +
  geom_density_ridges(
    jittered_points = TRUE,
    point_shape = "|", point_size = 2, size = 0.25,
    position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2,
    quantile_lines=TRUE, quantiles=2) +
  theme_classic()+
       labs(x = "Value", y="",title = "Distribution of support for democratic norms (Study 1)")+
  theme(
plot.title =element_text(size=16, colour="black", face = "bold"),
plot.subtitle = element_text(size=15, colour="black"),
axis.title.y = element_text(size=16, colour="black"),
axis.title.x = element_text(size=16,colour="black"),
axis.text.x = element_text(size=16,colour="black"),
axis.text.y =element_text(size=16,colour="black"),
legend.text = element_text(size = 16,colour="black"),
strip.text.x = element_text(size = 16,colour="black"),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_blank(),
legend.position = "none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank()
) +
  facet_wrap(~pid_cat)

ggsave(file= paste("figures/si_s1_desc_dn.png", sep=""),width =25, height = 17, units = "cm", dpi=320)

###

## pol violence

dfs<- data %>% dplyr::select(all_of(c("w2_viol_index", "pid_cat")))%>%
  mutate_all(~as.character(.)) %>%
pivot_longer(
cols = c( "w2_viol_index"),
names_to = "category",
values_to = "value") %>%
  mutate(emotion_category = case_when(str_detect(category, "viol")~ "PV index",
                            str_detect(category, "demnorms") ~ "DN index")) %>%
  mutate(value=as.numeric(value))
  
ggplot(dfs, aes(x = value, y = emotion_category, fill=emotion_category)) +
  geom_density_ridges(
    jittered_points = TRUE,
    point_shape = "|", point_size = 2, size = 0.25,
    position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2,
    quantile_lines=TRUE, quantiles=2) +
  theme_classic()+
       labs(x = "Value", y="",title = "Distribution of support for political violence (Study 1)")+
  theme(
plot.title =element_text(size=16, colour="black", face = "bold"),
plot.subtitle = element_text(size=15, colour="black"),
axis.title.y = element_text(size=16, colour="black"),
axis.title.x = element_text(size=16,colour="black"),
axis.text.x = element_text(size=16,colour="black"),
axis.text.y =element_text(size=16,colour="black"),
legend.text = element_text(size = 16,colour="black"),
strip.text.x = element_text(size = 16,colour="black"),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_blank(),
legend.position = "none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank()
) +
  facet_wrap(~pid_cat)

ggsave(file= paste("figures/si_s1_desc_pv.png", sep=""),width =25, height = 17, units = "cm", dpi=320)


### ap
dv_cols <- data %>% select(starts_with(c("w2_ap_", "therm")))   %>% colnames(.) 


dfs<- data %>% dplyr::select(all_of(c(dv_cols,"pid_cat")))%>%
  mutate_all(~as.character(.)) %>%
pivot_longer(
cols = all_of(c(dv_cols)),
names_to = "category",
values_to = "value") %>%
  mutate(Model=category,
    emotion_category = case_when(
      str_detect(Model, "ap_party") ~ "AP party",
      str_detect(Model, "ap_voters") ~ "AP voters",
      str_detect(Model, "ap_outgroup_party|therm_poloutparty") ~ "Therm (Out-party)",
      str_detect(Model, "ap_ingroup_party|therm_polinparty") ~ "Therm (In-party)",
      str_detect(Model, "ap_outgroup_voters|therm_votersoutparty") ~ "Therm (Out-voters)",
      str_detect(Model, "ap_ingroup_voters|therm_votersinparty") ~ "Therm (In-voters)",
      TRUE ~ "Other")) %>%
  mutate(value=as.numeric(value))
  
  
  

library(ggplot2)
ggplot(dfs, aes(x = value, y = emotion_category, fill=emotion_category)) +
  geom_density_ridges(
    jittered_points = TRUE,
    point_shape = "|", point_size = 2, size = 0.25,
    position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2,
    quantile_lines=TRUE, quantiles=2) +
  theme_classic()+
       labs(x = "Value", y="",title = "Distribution of affective polarization (Study 1)")+
  theme(
plot.title =element_text(size=16, colour="black", face = "bold"),
plot.subtitle = element_text(size=15, colour="black"),
axis.title.y = element_text(size=16, colour="black"),
axis.title.x = element_text(size=16,colour="black"),
axis.text.x = element_text(size=16,colour="black"),
axis.text.y =element_text(size=16,colour="black"),
legend.text = element_text(size = 16,colour="black"),
strip.text.x = element_text(size = 16,colour="black"),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "grey"),
legend.title=element_blank(),
legend.position = "none",
panel.grid.major = element_blank(), panel.grid.minor = element_blank()
) +
  facet_wrap(~pid_cat)

ggsave(file= paste("figures/si_s1_desc_ap.png", sep=""),width =25, height = 17, units = "cm", dpi=320)

# stats for in-text description, Appendix

sd(data$w2_ap_party[data$pid_cat=="Democrats"])
summary(data$w2_ap_party[data$pid_cat=="Democrats"])

summary(data$w2_ap_outgroup_party[data$pid_cat=="Democrats"])

sd(data$w2_ap_outgroup_party[data$pid_cat=="Democrats"])

summary(data$w2_ap_outgroup_voters[data$pid_cat=="Democrats"])

sd(data$w2_ap_outgroup_voters[data$pid_cat=="Democrats"])
```







# SI, Balance checks


```{r balance2, echo=F, results='asis'}

my_summarise <- function(data, group_var, summarise_var) {
  data %>%
    group_by(across({{ group_var }})) %>% 
    summarise(across({{ summarise_var }}, ~ paste(round(mean(., na.rm = T), digits = 2), " (", round(sd(., na.rm = T),digits = 2), ")", sep=""), .names = "{.col}")) #get mean and SD for each variable
}




subset <- data

balancetab <-  my_summarise(subset, w2_treatment_cat,  c(w1_gender_female, w1_prolific_age, w1_education_advanced, w1_ethnicity_white, w1_income_above70k,w1_partyid_num.1, w1_ap_party,  w1_ap_voters, w1_viol_index,w1_party_importance_num, w1_outgroup_negative, w1_ingroup_positive, w1_anxiety_outgroup_factor, w1_aversion_outgroup_factor)) %>%
  pivot_longer(cols= ! w2_treatment_cat, names_to="variable",values_to="value") %>%
pivot_wider(names_from =  w2_treatment_cat, values_from =value) %>%
  rename("Variable"="variable") %>%
  relocate(Variable)







controlvars <- c("w1_gender_female", "w1_prolific_age", "w1_education_advanced", "w1_ethnicity_white", "w1_income_above70k",  "w1_partyid_num.1","w1_ap_party","w1_ap_voters",  "w1_viol_index","w1_party_importance_num", "w1_outgroup_negative", "w1_ingroup_positive",  "w1_anxiety_outgroup_factor", "w1_aversion_outgroup_factor")

my_pvalue <- function(summarise_var) {
lm1 <- lm_robust((eval(parse(text=paste(summarise_var, sep="")))) ~ w2_treatment_cat,  data=data)

model <- lm1 %>% tidy() %>% select(c(p.value, term)) %>% mutate(term=case_when(str_detect(tolower(term), "anger") ~ "Anger",
                                                                      str_detect(tolower(term), "worry") ~ "Worry",
                                                                      str_detect(tolower(term), "cept") ~ "Placebo")) %>%
  filter(term!="Placebo") %>%
  pivot_longer(cols= ! term, names_to="variable",values_to="value") %>%
pivot_wider(names_from =  term, values_from =value) %>%
  rename("Variable"="variable") %>%
  relocate(Variable)%>% mutate(Variable=paste0(summarise_var))
return(model)
}

pvalue <- data.frame() 

for (i in controlvars) {
  m <- my_pvalue(i)
pvalue <- rbind(pvalue, m)
}

balance <- balancetab %>% mutate(Anger= case_when(pvalue$Anger<0.05& pvalue$Anger>=0.01 ~ paste(Anger, "**"),
                                        pvalue$Anger<0.01 ~ paste(Anger, "***"),
                                        pvalue$Anger<0.1 & pvalue$Anger>=0.05  ~ paste(Anger, "*"),
                                        pvalue$Anger>=0.1   ~ paste(Anger))) %>%
 mutate(Worry= case_when(pvalue$Worry<0.05& pvalue$Worry>=0.01 ~ paste(Worry, "**"),
                                        pvalue$Worry<0.01 ~ paste(Worry, "***"),
                                        pvalue$Worry<0.1 & pvalue$Worry>=0.05  ~ paste(Worry, "*"),
                                        pvalue$Worry>=0.1   ~ paste(Worry)))


balance <- balance %>%
  mutate(Variable=case_when(str_detect(Variable, "gender")~"Gender=Female (0/1)",
                            str_detect(Variable, "age")~"Age (18-79)",
                            str_detect(Variable, "education")~"Education=Advanced (0/1)",
                            str_detect(Variable, "white")~"Ethnicity=White (0/1)",
                            str_detect(Variable, "income")~"Income=Above70k (0/1)",
                            str_detect(Variable, "ap_voters")~"AP voters (-100 to +100)",
                            str_detect(Variable, "ap_party")~"AP parties (-100 to +100)",
                            str_detect(Variable, "partyid")~"PID=Republican (0/1)",
                            str_detect(Variable, "viol_index")~"Support pol. violence (0-1)",
                            str_detect(Variable, "outgroup_negative")~"Neg. partisanship (1-5)",
                            str_detect(Variable, "ingroup_positive")~"Pos. partisanship (1-5)",
                            str_detect(Variable, "aversion")~"Outgroup aversion (1-5)",
                            str_detect(Variable, "anxiety")~"Outgroup anxiety (1-5)",
                            str_detect(Variable, "w1_party_importance_num") ~ "Party importance (1-5)"))

library(stargazer)
stargazer(balance, summary = F, rownames = F, title= paste ("Study 1: Balance on key pre-treatment covariates",  sep="" ),  notes = c("Mean and (SD) for key covariates." , "Stars show significant differences between the treatment and the placebo condition.", "***p$<$0.01, **p$<$0.05, *p$<$0.1"), out=paste0("figures/s1_balancetable_", "wholesample", ".tex"))



```




# SI, Compare sample to ANES
```{r anes}

# Step 1: Manually download ANES 2022 Pilot data in csv format
# More information and download: https://electionstudies.org/data-center/2022-pilot-study/
# Once downloaded, unzip and save the whole downloaded folder in the same directory as the code file, then load the file in using the code below:


anes <- read.csv("anes_pilot_2022_csv_20221214/anes_pilot_2022_csv_20221214.csv")




anes <- anes %>% mutate(w1_education_advanced=case_when(educ>3~ 1,
                                                        TRUE ~ 0),
                        w1_gender_female=case_when(gender==2~1,
                                                   TRUE~0),
                        w1_prolific_age= 2022-as.numeric(birthyr_dropdown),
                        w1_ethnicity_white = case_when(rwh ==1~1,
                        TRUE~0),
                        w1_partyid= case_when(pid_x <4~"Democrats",
                                              pid_x >4~"Republicans"),
                        dem_therm = ftdem,
                        rep_therm = ftrep,
                        w1_ap_voters= case_when(w1_partyid=="Democrats" ~ dem_therm-rep_therm,
                                                w1_partyid=="Republicans" ~ rep_therm-dem_therm,
                                                is.na(w1_partyid) ~ NA_real_),
                        imppartyid_nona = replace_na(imppartyid, -1),
                        w1_party_importance_normalized = (as.numeric(imppartyid) - 1) / (5 - 1))
                        
anes_subset <- anes %>% select(w1_gender_female, w1_prolific_age, w1_education_advanced, w1_ethnicity_white,  w1_ap_voters, w1_partyid, w1_party_importance_normalized) %>%
  mutate(survey="ANES") %>%
  filter(!is.na(w1_partyid))



data_subset <- data %>% select(w1_gender_female, w1_prolific_age, w1_education_advanced, w1_ethnicity_white,  w2_ap_voters, w1_partyid, w2_party_importance_num) %>%
  mutate(survey="Sample") %>%
  mutate(w1_party_importance_normalized = w2_party_importance_num-1/(5-1)) %>%
  rename(w1_ap_voters=w2_ap_voters) %>%
dplyr::select(!w2_party_importance_num)

comb <- rbind(anes_subset, data_subset) %>% mutate (com_pid = paste(survey, w1_partyid))



balancetab <-  my_summarise(comb, com_pid,  c(w1_gender_female, w1_prolific_age, w1_education_advanced, w1_ethnicity_white,  w1_ap_voters)) %>%
  pivot_longer(cols= ! com_pid, names_to="variable",values_to="value") %>%
pivot_wider(names_from =  com_pid, values_from =value) %>%
  rename("Variable"="variable") %>%
  relocate(Variable)

balance <- balancetab %>% 
  mutate(Variable=case_when(str_detect(Variable, "gender")~"Gender=Female (0/1)",
                            str_detect(Variable, "age")~"Age",
                            str_detect(Variable, "education")~"Education=Advanced (0/1)",
                            str_detect(Variable, "white")~"Ethnicity=White (0/1)",
                            str_detect(Variable, "income")~"Income=Above70k (0/1)",
                            str_detect(Variable, "ap_voters")~"AP voters (-100 to +100)",
                            str_detect(Variable, "ap_party")~"AP parties (-100 to +100)",
                            str_detect(Variable, "partyid")~"PID=Republican (0/1)",
                            str_detect(Variable, "viol_index")~"Support pol. violence (0-1)",
                            str_detect(Variable, "outgroup_negative")~"Neg. partisanship (1-5)",
                            str_detect(Variable, "ingroup_positive")~"Pos. partisanship (1-5)",
                            str_detect(Variable, "aversion")~"Outgroup aversion (1-5)",
                            str_detect(Variable, "anxiety")~"Outgroup anxiety (1-5)"))

stargazer(balance, summary = F, rownames = F, title= "Comparison between sample characteristics and ANES pilot survey",  notes = c("Mean and (SD) for key covariates.", "ANES pilot survey was conducted in November 2022"), out=paste0("figures/si_balancetable_", "anes", ".tex"))




```

## SI Regression tables


```{r regtables-s2-funcs}


library(texreg)
library(estimatr)
library(rlang)




# Define control variables
controlvars <- c("w1_gender_female", "w1_prolific_age", "w1_education_advanced", 
                 "w1_ethnicity_white", "w1_income_above70k", "w1_partyid",
                 "w1_party_importance_num", "w1_outgroup_negative", "w1_ingroup_positive", "w1_ap_party", "w1_ap_voters")


# Main function to run models 
run_models <- function(outcome, data) {
  control_formula <- paste(controlvars, collapse = " + ")

  models <- list(
    lm1 = lm_robust(as.formula(paste(outcome, "~  w2_treatment_tvscontrol")), data = data),
    lm2 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat")), data = data),
    lm3 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat*w1_outgroup_negative")), data = data),
    lm4 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat*w1_party_importance_num")), data = data),
        lm5 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat*w1_ingroup_positive")), data = data),
    lm6 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat +", control_formula)), data = data)
  )



  return(models)
}

# Main function to run models 
run_models_pret <- function(outcome, data, pretvar) {
  control_formula <- paste(controlvars, collapse = " + ")

  models <- list(
    lm1 = lm_robust(as.formula(paste(outcome, "~  w2_treatment_tvscontrol +", pretvar)), data = data),
    lm2 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat +", pretvar)), data = data),
    lm3 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat*w1_outgroup_negative +", pretvar)), data = data),
    lm4 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat*w1_party_importance_num +", pretvar)), data = data),
        lm5 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat*w1_ingroup_positive +", pretvar)), data = data),
    lm6 = lm_robust(as.formula(paste(outcome, "~ w2_treatment_cat +",pretvar,"+", control_formula)), data = data)
  )



  return(models)
}

# rename coefficients in texreg

coef_labels <- list(
  "(Intercept)"= "Intercept",
  "w2_treatment_tvscontrolTreatment" = "Treatment=Pooled",
  "w2_treatment_catAnger" = "Treatment=Anger",
  "w2_treatment_catWorry" = "Treatment=Worry",
  "w1_gender_female" = "Gender=Female",
  "w1_ingroup_positive" = "Pos. partisanship",
  "w1_outgroup_negative" = "Neg. partisanship",
  "w1_prolific_age" = "Age",
  "w1_education_advanced" = "Education=Degree",
  "w1_ethnicity_white" = "Ethnicity=White",
  "w1_income_above70k" = "High income",
  "w1_partyidRepublicans" = "Party ID: Republican",
  "w1_party_importance_num" = "Party importance",
  "w1_ap_party" = "AP (politicians)",
  "w1_ap_voters" = "AP (voters)",
  "w2_treatment_catAnger:w1_party_importance_num" = "Treatment=Anger:Party importance",
   "w2_treatment_catWorry:w1_party_importance_num" = "Treatment=Worry:Party importance",
  "w2_treatment_catAnger:w1_ingroup_positive" ="Treatment=Anger:Pos. partisanship",
  "w2_treatment_catWorry:w1_ingroup_positive" = "Treatment=Worry:Pos. partisanship",
  "w2_treatment_catAnger:w1_outgroup_negative" = "Treatment=Anger:Neg. partisanship",
  "w2_treatment_catWorry:w1_outgroup_negative" = "Treatment=Worry:Neg. partisanship",
  "w1_viol_index" = "Pre-t. support for violence index",
  "w1_pv4_normalized" = "Pre-t. support election-specific violence"
  
)



# get tex file 

regtables <- function(outcomevar, outcomenameshort, outcomenamelong){
 models <- run_models(outcomevar, data = data) 
 regfile <- texreg(models, include.ci = FALSE, 
                    digits = 3,
                    stars = c(0.01,0.05,0.1),
                    custom.model.names=c("M1", "M2", "M3", "M4", "M5", "M6"),
                  custom.coef.map = coef_labels,
                    caption= paste("Study 1: Effect of electoral loss treatments on \n DV: ", outcomenamelong,  sep=""),
                  custom.note = "\\item %stars. ",
                 threeparttable = T,
                    label= paste("table:s1_", outcomenameshort, "_reg", sep=""),
                 use.packages = FALSE, #this prevents the usepackage option from printing in the table in latex,
                 include.rmse = FALSE
                    )
print(regfile)
print(regfile, file =paste("figures/s1_", outcomenameshort, "_reg.tex", sep=""))
}

regtables_pret <- function(outcomevar, outcomenameshort, outcomenamelong, pretvar){
 models <- run_models_pret(outcomevar, data = data, pretvar) 
 regfile <- texreg(models, include.ci = FALSE, 
                    digits = 3,
                    stars = c(0.01,0.05,0.1),
                    custom.model.names=c("M1", "M2", "M3", "M4", "M5", "M6"),
                  custom.coef.map = coef_labels,
                    caption= paste("Study 1: Effect of electoral loss treatments on \n DV: ", outcomenamelong,  sep=""),
                  custom.note = "\\item %stars. ",
                 threeparttable = T,
                    label= paste("table:s1_", outcomenameshort, "_reg", sep=""),
                 use.packages = FALSE, #this prevents the usepackage option from printing in the table in latex,
                 include.rmse = FALSE
                    )
print(regfile)
print(regfile, file =paste("figures/s1_", outcomenameshort, "_reg.tex", sep=""))
}


```

# Apply functions to generate regression tables

```{r applyreg}

library(texreg)


regtables_pret("w2_viol_index","w2_viol_index","change in support for political violence index (controlling for wave 1)", "w1_viol_index")

regtables("prepost_viol_index", "prepost_viol_index", "change in support for political violence index (change score)")


regtables("w2_dem_norms_index", "demnorms_index", "support for democratic norms (index)")

regtables_pret("w2_pv4_normalized","w2_pv4_normalized","change in support for election-specific political violence (controlling for wave 1)", "w1_pv4_normalized")

regtables("prepost_viol_4", "pv4", "change in support for election-specific violence (change score)")



regtables("worried_bin", "worried_bin", "feeling very or extremely worried about the election outcome (binary)")

regtables("angry_bin", "angry_bin", "feeling very or extremely angry about the election outcome (binary)")



```